package com.yuven.baselib.component;

import android.content.Context;
import android.os.Bundle;

import androidx.annotation.MainThread;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.yuven.baselib.component.eventbus.Event;
import com.yuven.baselib.component.eventbus.EventBusUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * @author :        Yuven
 * @date :          2022/7/6 6:17 下午
 * @desc :
 */
public class FrameBaseEmptyActivity extends AppCompatActivity {
    protected AppCompatActivity mActivity;
    protected Context mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = mActivity = this;
        if (registerEventBus()) {
            EventBusUtil.register(this);
        }
    }


    /**
     * 子类接受事件 重写[.handleEvent]
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBus(Event<Object> event) {
        if (event != null) {
            handleEvent(event);
        }
    }


    @Override
    protected void onDestroy() {
        if (registerEventBus()) {
            EventBusUtil.unregister(this);
        }
        super.onDestroy();
    }

    /**
     * 需要接收事件 重写该方法 并返回true
     */
    protected boolean registerEventBus() {
        return false;
    }

    @MainThread
    protected void handleEvent(Event<Object> event) {
    }

    @MainThread
    protected void handleStickyEvent(Event<Object> event) {
    }

    @Override
    public void onBackPressed() {
        if (!interceptBackPressed()) {
            super.onBackPressed();
        }
    }

    /**
     * 拦截事件
     */
    protected final Boolean interceptBackPressed() {
        int size = getSupportFragmentManager().getFragments().size();
        for (int i = 0; i < size; i++) {
            Fragment fragment = getSupportFragmentManager().getFragments().get(i);
            if (fragment instanceof BackPressedListener) {
                if (((BackPressedListener) fragment).handleBackPressed()) {
                    return true;
                }
            }
        }
        return false;
    }
}
